package org.pskovgu.pskovbus;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class StationDataSource {
	private SQLiteDatabase database;
	  private StationDbOpenHelper dbHelper;
	  private String[] allColumns = { 
			  StationDbOpenHelper.STATION_ID,
			  StationDbOpenHelper.INNER_NAME,
			  StationDbOpenHelper.NAME			  
	  };

	  public StationDataSource(Context context) {
	    dbHelper = new StationDbOpenHelper(context);
	  }

	  public void open() throws SQLException {
	    database = dbHelper.getWritableDatabase();
	  }

	  public void close() {
	    dbHelper.close();
	  }

	  public Station createStation(String inner_name, String name) {
	    ContentValues values = new ContentValues();
	    values.put(StationDbOpenHelper.INNER_NAME, inner_name);
	    values.put(StationDbOpenHelper.NAME, name);
	    long insertId = database.insert(StationDbOpenHelper.TABLE_NAME, null, values);
	    Cursor cursor = database.query(StationDbOpenHelper.TABLE_NAME,
	        allColumns, StationDbOpenHelper.STATION_ID + " = " + insertId, null,
	        null, null, null);
	    cursor.moveToFirst();
	    Station newStation = cursorToStation(cursor);
	    cursor.close();
	    return newStation;
	  }

	  public void deleteStation(Bus comment) {
	    long id = comment.getId();
	    System.out.println("Station deleted with id: " + id);
	    database.delete(StationDbOpenHelper.TABLE_NAME, StationDbOpenHelper.STATION_ID
	        + " = " + id, null);
	  }

	  public List<Station> getAllStations() {
	    List<Station> stations = new ArrayList<Station>();

	    Cursor cursor = database.query(StationDbOpenHelper.TABLE_NAME,
	        allColumns, null, null, null, null, null);

	    cursor.moveToFirst();
	    while (!cursor.isAfterLast()) {
	      Station st = cursorToStation(cursor);
	      stations.add(st);
	      cursor.moveToNext();
	    }
	    // Make sure to close the cursor
	    cursor.close();
	    return stations;
	  }
	  
	  public List<Station> getStationsById(long l) {		  
		    List<Station> comments = new ArrayList<Station>();
		    String[] args = {Integer.toString((int) l)};

		    Cursor cursor = database.query(StationDbOpenHelper.TABLE_NAME,
		        allColumns, StationDbOpenHelper.STATION_ID+" = ?", args, null, null, null);

		    cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		    	Station comment = cursorToStation(cursor);
		    	comments.add(comment);
		    	cursor.moveToNext();
		    }
		    // Make sure to close the cursor
		    cursor.close();
		    return comments;
		    }

	  private Station cursorToStation(Cursor cursor) {
	    Station station = new Station();
	    station.setId(cursor.getLong(0));	    
	    station.setName(cursor.getString(2));
	    station.setInnerName(cursor.getString(1));
	    return station;
	  }

}
